package com.appology.buzz;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.buzz.Buzz;
import com.google.api.services.buzz.Buzz.Activities.Search;
import com.google.api.services.buzz.model.ActivityFeed;

public class RecentActivities extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String PARAMETER_NUM = "num";
	private static final String SEARCH_QUERY = "appology-chuck-norris.appspot.com";
	private static final String CONTENT_TYPE = "application/json";

	private static int num = 50;
	private static Buzz buzz;
	private static Search search;
	private static ActivityFeed activities;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		// Set the MIME type of the response as "application/json"
		resp.setContentType(CONTENT_TYPE);
		resp.setHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
		resp.setHeader("Last-Modified", new Date().toString());
		resp.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
		resp.setHeader("Pragma", "no-cache");
		// If the url parameter "num" is set, then that is how many
		// activities we will request, otherwise, we will default to 50
		if (req.getParameter(PARAMETER_NUM) != null) {
			try {
				num = Integer.parseInt(req.getParameter(PARAMETER_NUM));
			} catch (NumberFormatException e) {
				num = 50;
			}
		}

		// Instantiate a new Buzz object using only a transport and jsonFactory.
		// We don't need credentials because we are just searching, and a user
		// doesn't
		// have to be logged in for that.
		buzz = new Buzz(new NetHttpTransport(), new JacksonFactory());

		// Get an Activities Search object
		search = buzz.activities.search();

		// Set the query string to appology-chuck-norris.appspot.com
		// This will help us only return posts that were generated from
		// this app.
		search.q = SEARCH_QUERY;

		// Set the max returned results to whatever num is right now (default
		// 50)
		search.maxResults = num;

		// Execute the search and get the ActivityFeed back
		activities = search.execute();

		// the ActivityFeed's toString() function returns a json formatted list
		// We can just print it straight out to the screen.
		resp.getWriter().print(activities.toString());

	}

}
